package tree.medium;

import tree.TreeNode;

import java.util.Arrays;

/**
 * 106. 从中序与后序遍历序列构造二叉树
 */
public class BuildTree {

    public static void main(String[] args) {
        BuildTree buildTree = new BuildTree();
//        int[] inorder = {9, 3, 15, 20, 7};
        int[] inorder = {3, 1};
//        int[] postorder = {9, 15, 7, 20, 3};
        int[] postorder = {3, 1};
        System.out.println(buildTree.buildTree(inorder, postorder));
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {

        if (inorder.length == 0) {
            return null;
        }
        if (inorder.length == 1) {
            TreeNode treeNode = new TreeNode();
            treeNode.val = inorder[0];
            return treeNode;
        }

        int rootVal = postorder[postorder.length - 1];
        int rootIndex = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (rootVal == inorder[i]) {
                rootIndex = i;
                break;
            }
        }
        TreeNode root = new TreeNode();
        root.val = rootVal;
        int[] leftInorder = Arrays.copyOfRange(inorder, 0, rootIndex);
        int[] rightInorder = Arrays.copyOfRange(inorder, rootIndex + 1, postorder.length);
        int[] leftPostorder = Arrays.copyOfRange(postorder, 0, leftInorder.length);
        int[] rightPostorder = Arrays.copyOfRange(postorder, leftInorder.length, postorder.length - 1);
        root.left = buildTree(leftInorder, leftPostorder);
        root.right = buildTree(rightInorder, rightPostorder);

        return root;
    }
}
